<template>
  <div class="wepage_edit cl">
    <div class="left scrollbar">
      <!-- 页面信息 -->
      <div v-show="!curEditType" class="page_control">
        <el-form ref="form1" class="page_info" :model="page" :rules="rules" label-width="80px">
          <el-form-item label="页面名称" prop="name">
            <el-input type="text" v-model="page.name" :maxlength="100"></el-input>
          </el-form-item>
          <el-form-item label="内容性质" prop="attrId">
            <el-select v-model="page.attrId" clearable>
              <el-option v-for="item,n in attrs" :value="item.id" :label="item.name" :key="item.id.toString()">
                {{item.name}}
              </el-option>
            </el-select>
          </el-form-item>
          <p>请选择下方控件到右侧的编辑区域，并点击区域编辑内容。</p>
        </el-form>
        <el-form class="page_pos">
          <el-form-item label="上下边距" label-width="70px">
            <el-slider v-model="page.node.paddingV"></el-slider>
          </el-form-item>
          <el-form-item label="左右边距" label-width="70px">
            <el-slider v-model="page.node.paddingH"></el-slider>
          </el-form-item>
          <el-form-item label="背景颜色" label-width="70px">
            <el-color-picker v-model="page.node.bgc"></el-color-picker>
          </el-form-item>
          <el-form-item label="背景图片" label-width="70px">
            <el-button type="primary" size="small" @click="dialog2=true">从素材库选择</el-button>
            <el-button v-if="page.node.bg" type="text" @click="page.node.bg = ''">删除</el-button>
          </el-form-item>
        </el-form>
        <ul class="controls">
          <li @click="addComponent('text')">
            <i class="icon icon-text"></i>
            <p>文本</p>
          </li>
          <li @click="addComponent('image')">
            <i class="icon icon-tupian"></i>
            <p>图片</p>
          </li>
          <li @click="addComponent('separator')">
            <i class="icon icon-fengefu"></i>
            <p>分隔符</p>
          </li>
          <li @click="addComponent('audio')">
            <i class="icon icon-yuyin"></i>
            <p>音频</p>
          </li>
          <li @click="addComponent('video')">
            <i class="icon icon-shipin"></i>
            <p>视频</p>
          </li>
          <li @click="addComponent('button')">
            <i class="icon icon-anniu"></i>
            <p>按钮</p>
          </li>
          <li @click="addComponent('form')">
            <i class="icon icon-biaodan"></i>
            <p>表单</p>
          </li>
          <li @click="addComponent('qrCode')">
            <i class="icon icon-erweima"></i>
            <p>二维码</p>
          </li>
          <li @click="addComponent('cube')">
            <i class="icon icon-mofang"></i>
            <p>魔方</p>
          </li>
          <li @click="addComponent('banner')">
            <i class="icon icon-banner"></i>
            <p>banner</p>
          </li>
          <li @click="addComponent('card')">
            <i class="icon icon-mingpian"></i>
            <p>名片</p>
          </li>
          <li @click="addComponent('html')">
            <i class="icon icon-html"></i>
            <p>html</p>
          </li>
        </ul>
      </div>
      <!-- 控件编辑器 -->
      <div v-show="curEditType" class="editor_box">
        <we-text-editor ref="textEditor" v-show="curEditType==='text'" :data="curEdit.data"></we-text-editor>
        <we-image-editor ref="imageEditor" v-if="curEditType==='image'" :data="curEdit.data"></we-image-editor>
        <we-separator-editor ref="separatorEditor" v-if="curEditType==='separator'"
                             :data="curEdit.data"></we-separator-editor>
        <we-audio-editor ref="audioEditor" v-if="curEditType==='audio'" :data="curEdit.data"></we-audio-editor>
        <we-video-editor ref="videoEditor" v-if="curEditType==='video'" :data="curEdit.data"></we-video-editor>
        <we-button-editor ref="buttonEditor" v-if="curEditType==='button'" :data="curEdit.data"></we-button-editor>
        <we-code-editor ref="codeEditor" v-if="curEditType==='qrCode'" :data="curEdit.data"></we-code-editor>
        <we-form-editor ref="formEditor" v-if="curEditType==='form'" :data="curEdit.data"
                        @select="id => page.formId=id"></we-form-editor>
        <we-html-editor ref="htmlEditor" v-if="curEditType==='html'" :data="curEdit.data"></we-html-editor>
        <we-cube-editor ref="cubeEditor" v-if="curEditType==='cube'" :data="curEdit.data"></we-cube-editor>
        <we-banner-editor ref="bannerEditor" v-if="curEditType==='banner'" :data="curEdit.data"></we-banner-editor>
        <we-card-editor ref="cardEditor" v-if="curEditType==='card'" :data="curEdit.data"></we-card-editor>
        <div class="btn_wrap">
          <el-button type="primary" @click="handleConfirmEdit(saveEdit)">确定</el-button>
          <el-button @click="handleEditorCancel">取消</el-button>
        </div>
      </div>
      <!-- 微信页面信息 -->
      <!--       <div v-show="!curEditType" class="wx_info">
              <h3>如果页面在微信(必须是已认证服务号)中展示，需要设置如下信息：</h3>
              <el-form label-width="40px">
                <el-form-item label="微信">
                  <el-select v-model="page.appid">
                    <el-option v-for="item,n in wechatList.list" :value="item.appid" :label="item.nickName" :key="n.toString()">
                      {{item.nickName}}
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="标题">
                  <el-input></el-input>
                </el-form-item>
                <el-form-item label="摘要">
                  <el-input></el-input>
                </el-form-item>
                <el-form-item label="封面">
                  <el-upload
                    class="upload"
                    :action="baseUrl + '/content/source/upload/image'"
                    :data="params"
                    :headers="headers"
                    :show-file-list="false"
                    :before-upload="handleBeforeUpload">
                    <el-button type="primary">上传封面</el-button>
                  </el-upload>
                </el-form-item>
              </el-form>
            </div> -->
    </div>
    <div class="right scrollbar">
      <div class="wepage_main"
           :style="{padding: page.node.paddingV + 'px ' + page.node.paddingH + 'px', backgroundImage: page.node.bg && `url('${page.node.bg}')`, backgroundSize: '100% auto',backgroundRepeat: 'repeat', backgroundColor: page.node.bgc}">
        <draggable ref="drag" v-model="page.node.components" :size="page.node.components.length">
          <edit-box ref="editBox" v-for="item,n in page.node.components" @delete="deleteNode(n)" @edit="editNode(n)"
                    :key="n.toString()">
            <we-text v-if="item.type==='text'" :data="item.data"></we-text>
            <we-image v-else-if="item.type==='image'" :data="item.data"></we-image>
            <we-separator v-else-if="item.type==='separator'" :data="item.data"></we-separator>
            <we-audio v-else-if="item.type==='audio'" :data="item.data"></we-audio>
            <we-video v-else-if="item.type==='video'" :data="item.data"></we-video>
            <we-button v-else-if="item.type==='button'" :data="item.data"></we-button>
            <we-code v-else-if="item.type==='qrCode'" :data="item.data"></we-code>
            <we-form v-else-if="item.type==='form'" :data="item.data"></we-form>
            <we-html v-else-if="item.type==='html'" :data="item.data"></we-html>
            <we-cube v-else-if="item.type==='cube'" :data="item.data"></we-cube>
            <we-banner v-else-if="item.type==='banner'" :data="item.data"></we-banner>
            <we-card v-else-if="item.type==='card'" :data="item.data"></we-card>
          </edit-box>
        </draggable>
      </div>
    </div>
    <div class="bottom">
      <el-row>
        <el-checkbox v-model="page.groupType" :true-label="1" :false-label="0">上传到事业部内容库<i
          style="color:#bbb">（直接上传，不审核）</i></el-checkbox>
      </el-row>
      <el-row v-if="showCommonType">
        <el-checkbox v-model="page.commonType" :true-label="1" :false-label="0">上传到公共内容库<i style="color:#bbb">（将提交品牌VI审核）</i>
        </el-checkbox>
      </el-row>
      <el-row>
        <el-button v-if="id=='new'||pageDetail.save" type="primary" @click="handleSave(false)">保存</el-button>
        <el-button v-if="id!=='new'" type="primary" @click="handleSave(true)">另存为</el-button>
        <el-button @click="handlePreviewClick" :disabled="id==='new'">预览</el-button>
      </el-row>
    </div>
    <!-- 预览二维码 -->
    <el-dialog :visible.sync="dialog" custom-class="dialog_preview">
      <img :src="`data:image/png;base64,${qrImg}`" alt="">
      <div slot="footer">
        <el-button @click="dialog=false;">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 选择图片 -->
    <el-dialog ref="dialog" title="选择图片" :visible.sync="dialog2">
      <dialog-image></dialog-image>
      <div slot="footer">
        <el-button type="primary" @click="handleSelectImage">确定</el-button>
        <el-button @click="dialog2=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {mapActions, mapState} from 'vuex'
  import env from '@/config/env'
  import draggable from 'vuedraggable'
  import editBox from '@/components/common/content/wePage/editBox'
  import weText from '@/components/common/content/wePage/weText'
  import weImage from '@/components/common/content/wePage/weImage'
  import weSeparator from '@/components/common/content/wePage/weSeparator'
  import weVideo from '@/components/common/content/wePage/weVideo'
  import weAudio from '@/components/common/content/wePage/weAudio'
  import weButton from '@/components/common/content/wePage/weButton'
  import weCode from '@/components/common/content/wePage/weCode'
  import weForm from '@/components/common/content/wePage/weForm'
  import weHtml from '@/components/common/content/wePage/weHtml'
  import weCube from '@/components/common/content/wePage/weCube'
  import weBanner from '@/components/common/content/wePage/weBanner'
  import weCard from '@/components/common/content/wePage/weCard'
  import weTextEditor from '@/components/common/content/wePage/weTextEditor'
  import weImageEditor from '@/components/common/content/wePage/weImageEditor'
  import weSeparatorEditor from '@/components/common/content/wePage/weSeparatorEditor'
  import weVideoEditor from '@/components/common/content/wePage/weVideoEditor'
  import weAudioEditor from '@/components/common/content/wePage/weAudioEditor'
  import weButtonEditor from '@/components/common/content/wePage/weButtonEditor'
  import weCodeEditor from '@/components/common/content/wePage/weCodeEditor'
  import weFormEditor from '@/components/common/content/wePage/weFormEditor'
  import weHtmlEditor from '@/components/common/content/wePage/weHtmlEditor'
  import weCubeEditor from '@/components/common/content/wePage/weCubeEditor'
  import weBannerEditor from '@/components/common/content/wePage/weBannerEditor'
  import weCardEditor from '@/components/common/content/wePage/weCardEditor'
  import dialogImage from '@/components/common/content/dialogImage'
  import css from 'css-loader!@/style/wepage.wecss'
  import js from 'raw-loader!./wepagejs'
  import 'vue-style-loader!css-loader!@/style/wepage.wecss'

  export default {
    components: {
      draggable,
      editBox,
      dialogImage,
      weText,
      weImage,
      weAudio,
      weVideo,
      weSeparator,
      weButton,
      weCode,
      weForm,
      weHtml,
      weCube,
      weBanner,
      weCard,
      weTextEditor,
      weImageEditor,
      weSeparatorEditor,
      weAudioEditor,
      weVideoEditor,
      weButtonEditor,
      weCodeEditor,
      weFormEditor,
      weHtmlEditor,
      weCubeEditor,
      weBannerEditor,
      weCardEditor
    },
    data() {
      return {
        id: this.$route.params.id,
        page: {
          name: '',
          attrId: '',
          groupType: 0,
          commonType: 0,
          node: {
            paddingH: 20,
            paddingV: 20,
            bgc: '#fff',
            bg: '',
            components: [{
              type: 'text',
              data: {
                content: '<p style="text-align: center;"><span style="font-size: 24px;">请编辑页面标题</span></p>',
                borderColor: '#666',
                borderWidth: 0,
                padding: 0,
                margin: 0
              }
            }]
          }
        },
        rules: {
          name: {required: true, message: '请输入页面名称', trigger: 'blur'},
          attrId: {required: true, message: '请选择内容性质'}
        },
        curEdit: {},
        curEditType: '',
        curEditTempObj: {},
        qrImg: '',
        showCommonType: true,
        dialog: false,
        dialog2: false,
        saveEdit: 'save',
        editIndex: 0
      }
    },
    mounted() {
      this.init()
    },
    computed: {
      ...mapState({
        attrs: state => state.contentManage.contentType,
        wechatList: state => state.wechatManage.wechatList,
        pageDetail: state => state.contentManage.wePageDetail,
        formDetail: state => state.contentManage.formDetail,
        selectedImg: state => state.sourceManage.selected
      }),
      baseUrl() {
        return env.baseUrl
      },
      // 文件上传附加的头部
      headers() {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      },
      // 文件上传附加的参数
      params() {
        return {
          contentType: 1,
          microPagImage: 1
        }
      }
    },
    methods: {
      ...mapActions(['getContentTypes', 'getWechatList', 'saveWePage', 'getWePageDetail', 'previewWepage']),
      async init() {
        const id = this.id
        if (id !== 'new') {
          await this.getWePageDetail(id)
          this.page.name = this.pageDetail.title
          this.page.node = JSON.parse(this.pageDetail.node)
          this.page.attrId = +this.$route.query.cs === 1 ? '' : this.pageDetail.attrId    // query.cs means clear select
          this.page.commonType = this.pageDetail.commonType
          // this.page.groupType = this.pageDetail.groupType
          this.page.formId = this.pageDetail.formId
          this.showCommonType = !this.pageDetail.commonType
        }
        this.getContentTypes()
        this.getWechatList()
      },

      // 初始化编辑器
      initEditor(initText = '') {
        const editor = this.$refs.textEditor
        editor.setContent(initText)
        editor.reset()
      },

      // 添加组件
      addComponent(type) {
        let obj
        switch (type) {
          case 'text':
            const str = '<p><span style="font-size: 24px;">请编辑文本</span></p>'
            obj = {
              type: 'text',
              data: {
                content: str,
                borderColor: '#666',
                borderWidth: 0,
                padding: 0,
                margin: 0
              }
            }
            this.initEditor(str)
            break
          case 'image':
            obj = {
              type: 'image',
              data: {
                link: '',
                url: '',
                richText: '',
                richTextX: 0,
                richTextY: 0
              }
            }
            break
          case 'separator':
            obj = {
              type: 'separator',
              data: {
                size: 1,
                top: 10,
                bottom: 10,
                color: '#d3d3d3'
              }
            }
            break
          case 'audio':
            obj = {
              type: 'audio',
              data: {
                url: ''
              }
            }
            break
          case 'video':
            obj = {
              type: 'video',
              data: {
                url: ''
              }
            }
            break
          case 'button':
            obj = {
              type: 'button',
              data: {
                content: '按钮',
                action: 'link',
                url: '',
                fontFamily: 'microsoft-yahei',
                fontWeight: 500,
                fontSize: '12',
                fontColor: '#fff',
                align: 'center',
                borderWidth: 0,
                borderColor: '#2eb2ed',
                borderRadius: 1,
                shadow: 1,
                size: 'medium',
                background: '#2eb2ed'
              }
            }
            break
          case 'qrCode':
            obj = {
              type: 'qrCode',
              data: {
                url: null,
                weId: null,
                codeId: null,
                image: null
              }
            }
            break
          case 'form':
            if (this.page.node.components.filter(item => item.type === 'form').length) {
              this.$message.warning('每个微页面只能有一个表单')
              break
            } else {
              obj = {
                type: 'form',
                data: {
                  id: null,
                  content: ''
                }
              }
              break
            }
          case 'html':
            obj = {
              type: 'html',
              data: {
                html: null
              }
            }
            break
          case 'cube':
            obj = {
              type: 'cube',
              data: {
                size: 4,
                areas: [],
                margin: 1
              }
            }
            break
          case 'banner':
            obj = {
              type: 'banner',
              data: {
                imgList: []
              }
            }
            break
          case 'card':
            obj = {
              type: 'card',
              data: {
                bgc: '#909090',
                img: ''
              }
            }
            break
        }
        this.curEdit = obj
        this.curEditType = type
        this.saveEdit = 'save'
        this.backups = this.$_.cloneDeep(obj)
        this.page.node.components.push(this.curEdit)
        this.editIndex = this.page.node.components.length - 1
      },

      handleConfirmEdit(type) {
        // if(type === 'save'){  //新建保存
        //   // this.page.node.components.push(this.curEdit)
        //   this.editIndex = 0
        // }else if(type === 'edit'){  //编辑
        //   // this.page.node.components[this.editIndex] = this.curEditTempObj
        //   this.$set(this.page.node.components, this.editIndex, this.curEdit)
        // }
        this.$set(this.page.node.components, this.editIndex, this.curEdit)
        this.curEditType = null
      },

      // 取消编辑组件
      handleEditorCancel() {
        this.curEdit.data = this.backups.data
        this.curEditType = null
        if (this.saveEdit === 'save') {
          this.page.node.components.pop()
        }
      },
      // 删除控件
      deleteNode(n) {
        this.page.node.components.splice(n, 1)
        this.curEditType = null
      },
      // 编辑控件
      editNode(n) {
        this.saveEdit = 'edit'
        this.editIndex = n
        this.curEdit = this.page.node.components[n]
        this.curEditType = this.page.node.components[n].type
        if (this.curEditType === 'text') {
          this.curEditTempObj = this.curEdit
          this.$refs.textEditor.setContent(this.curEdit.data.content)
          this.$nextTick()
            .then(() => {
              this.$refs.textEditor.reset()
            })
        }

        this.backups = this.$_.cloneDeep(this.curEdit)
      },
      // 上传前的检验
      handleBeforeUpload(file) {
        if (file.type.indexOf('image') === -1) {
          this.$message.warning('只可上传图片类型')
          return false
        }
      },
      saveCheck() {
        if (!this.page.node.components.length) {
          this.$message.warning('微页面内容不可为空')
          return false
        }
        return true
      },
      // 保存微页面
      handleSave(saveAs) {
        if (!this.saveCheck()) {
          return false
        }
        const id = saveAs ? null : this.id === 'new' ? null : this.id
        const commonType = saveAs ? 0 : this.page.commonType
        this.$refs['form1'].validate(async (valid, info) => {
          if (!valid) {
            const field = Object.keys(info)[0]
            const lack = info[field][0]
            this.$message.closeAll()
            this.$message.warning(lack.message)
            return false
          }
          const $edits = document.querySelectorAll('.wepage_main .edit_box')
          let html = ''
          let hasBanner = false
          $edits.forEach(item => {
            const $component = item.querySelector('.we_component')
            if ($component.getAttribute('class').indexOf('we_form') === -1) {
              html += $component.outerHTML
            } else {
              html += `<div class="el_form" data-id="${$component.getAttribute('data-id')}"></div>`
            }
            if ($component.getAttribute('class').indexOf('we_banner') !== -1) { // 判断是否有banner控件
              hasBanner = true
            }
          })
          const style = document.querySelector('.wepage_main').getAttribute('style')
          console.log(style)
          html = `<style>${css.toString()}</style><div class="we_page" style='${style}'>${html}</div>`
          hasBanner && (html += `<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.1.6/js/swiper.min.js"><` + '/script>')
          html += `<script>${js}<` + '/script>'
          const res = await this.saveWePage({
            id: id,
            attrId: this.page.attrId,
            title: this.page.name,
            formId: this.page.formId,
            content: html,
            commonType: commonType,
            groupType: this.page.groupType,
            node: this.page.node,
            publishStatus: 0
          })
          if (res.data.code === 1) {
            this.$message.success('保存成功')
            this.id === 'new' && (this.id = res.data.data.id)
            this.pageDetail.save = true
          }
        })
      },
      // 预览微页面
      async handlePreviewClick() {
        this.dialog = true
        const res = await this.previewWepage(this.id)
        this.qrImg = res.data.data.qrCode
      },
      // 选择背景图片
      handleSelectImage() {
        this.page.node.bg = this.selectedImg.url
        this.dialog2 = false
      }
    }
  }
</script>
<style lang="scss">
  .wepage_edit {
    .left {
      float: left;
      width: 426px;
      max-height: calc(100vh - 100px);
      min-height: 400px;
      overflow-y: auto;
    }
    .right {
      margin-left: 440px;
      width: 460px;
      border: 1px solid #ccc;
      max-height: calc(100vh - 100px);
      min-height: 400px;
      overflow-y: auto;
    }
    .page_info {
      padding: 15px;
      border: 1px solid #ccc
    }
    .editor_box {
      & {
        padding-bottom: 20px;
        background: #e7e3e3
      }
      .btn_wrap {
        margin-left: 134px;
      }
    }
    .page_pos {
      margin-top: 15px;
      padding: 15px;
      border: 1px solid #ccc
    }
    .controls {
      & {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
      }
      li {
        margin: 10px;;
        width: 80px;
        height: 80px;
        border: 1px solid #ccc;
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
      }
      p {
        user-select: none;
      }
      .icon {
        font-size: 36px;
        color: #777;
      }
    }
    .wx_info {
      & {
        margin-top: 10px;
        padding: 15px;
        border: 1px solid #ccc;
      }
      h3 {
        margin-bottom: 10px;
      }
    }
    .wepage_main {
      min-height: 400px;
      font: 12px/1.5 microsoft-yahei;
    }
    .bottom {
      & {
        float: left;
        margin-top: 20px;
        padding-top: 20px;
        width: 900px;
        margin-right: 100%;
        border-top: 1px solid #ccc;
      }
      .el-row {
        margin-bottom: 15px;
      }
    }
    .dialog_preview {
      & {
        width: 400px
      }
      img {
        display: block;
        margin: -20px auto;
        width: 360px;
      }
    }
  }
</style>
